document.addEventListener('DOMContentLoaded', function() {
    // 获取所有分类
    fetchCategories();

    // 应用筛选按钮点击事件
    document.getElementById('applyFilter').addEventListener('click', applyFilter);

    // 排序方式变更事件
    document.getElementById('sortSelect').addEventListener('change', function() {
        if (currentCategoryId) {
            fetchProductsByCategory(currentCategoryId);
        }
    });
});

let currentCategoryId = null;

// 获取所有分类
function fetchCategories() {
    fetch('/api/categories')
        .then(response => {
            if (!response.ok) {
                throw new Error('获取分类失败');
            }
            return response.json();
        })
        .then(categories => {
            const categoryList = document.getElementById('categoryList');
            categoryList.innerHTML = '';

            categories.forEach(category => {
                const categoryItem = document.createElement('div');
                categoryItem.className = 'category-item';
                categoryItem.dataset.id = category.id;
                categoryItem.innerHTML = category.name;

                categoryItem.addEventListener('click', function() {
                    fetchProductsByCategory(category.id);
                    setActiveCategory(category.id);
                });

                categoryList.appendChild(categoryItem);
            });

            // 如果有分类，加载第一个分类的商品
            if (categories.length > 0) {
                fetchProductsByCategory(categories[0].id);
                setActiveCategory(categories[0].id);
            }
        })
        .catch(error => {
            console.error('获取分类出错:', error);
        });
}

// 设置活跃的分类项
function setActiveCategory(categoryId) {
    const categoryItems = document.querySelectorAll('.category-item');
    categoryItems.forEach(item => {
        if (parseInt(item.dataset.id) === categoryId) {
            item.classList.add('active');
        } else {
            item.classList.remove('active');
        }
    });

    currentCategoryId = categoryId;
}

// 获取分类下的商品
function fetchProductsByCategory(categoryId) {
    const minPrice = document.getElementById('minPrice').value || 0;
    const maxPrice = document.getElementById('maxPrice').value || Infinity;
    const sort = document.getElementById('sortSelect').value;

    fetch(`/api/categories/${categoryId}/products?minPrice=${minPrice}&maxPrice=${maxPrice}&sort=${sort}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取商品失败');
            }
            return response.json();
        })
        .then(products => {
            displayProducts(products);
        })
        .catch(error => {
            console.error('获取商品出错:', error);
        });
}

// 应用筛选
function applyFilter() {
    if (currentCategoryId) {
        fetchProductsByCategory(currentCategoryId);
    }
}

// 显示商品列表
function displayProducts(products) {
    const productList = document.getElementById('productList');
    productList.innerHTML = '';

    if (products.length === 0) {
        productList.innerHTML = '<p style="text-align: center; padding: 20px;">暂无商品</p>';
        return;
    }

    const productGrid = document.createElement('div');
    productGrid.className = 'product-grid';

    products.forEach(product => {
        const productCard = document.createElement('div');
        productCard.className = 'product-card';

        productCard.innerHTML = `
            <img src="${product.image}" alt="${product.name}" class="product-image">
            <div class="product-info">
                <h3 class="product-name">${product.name}</h3>
                <p class="product-price">¥${product.price.toFixed(2)}</p>
                <p class="product-stock">库存: ${product.stock}</p>
                <p class="product-created-at">上架时间: ${new Date(product.createdAt).toLocaleString()}</p>
                <div class="product-actions">
                    <a href="product.html?id=${product.id}" class="view-details">查看详情</a>
                    <button class="add-to-cart" data-id="${product.id}">加入购物车</button>
                </div>
            </div>
        `;

        // 添加加入购物车按钮点击事件
        const addToCartBtn = productCard.querySelector('.add-to-cart');
        addToCartBtn.addEventListener('click', function() {
            addToCart(product.id);
        });

        productGrid.appendChild(productCard);
    });

    productList.appendChild(productGrid);
}

// 加入购物车
function addToCart(productId) {
    // 这里假设已经通过登录获取了用户ID，实际项目中应从令牌或会话中获取
    const userId = localStorage.getItem('userId');
    if (!userId) {
        alert('请先登录');
        return;
    }

    fetch('/api/cart/add', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ userId, productId, quantity: 1 }),
    })
        .then(response => {
            if (!response.ok) {
                throw new Error('加入购物车失败');
            }
            return response.json();
        })
        .then(data => {
            console.log('加入购物车成功:', data);
            alert('商品已加入购物车');
        })
        .catch(error => {
            console.error('加入购物车出错:', error);
            alert('加入购物车失败，请稍后再试');
        });
}